//
//  PhotoBrowserController.swift
//  Status
//
//  Created by Kylin on 16/3/31.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

private let PhotoBrowserCellID = "PhotoBrowserCellID"
class PhotoBrowserController: UIViewController {

    // MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserCollectionViewLayout())
    private lazy var closeBtn : UIButton = UIButton(title: "关 闭", BGcolor: UIColor.darkGrayColor(), fontSize: 14)
    private lazy var saveBtn : UIButton = UIButton(title: "保 存", BGcolor: UIColor.darkGrayColor(), fontSize: 14)
    
    // MARK:- 属性
    var indexPath : NSIndexPath
    var picURLs : [NSURL]
    
    // MARK:- 自定义构造函数
    init(indexPath : NSIndexPath,picURLs : [NSURL]){
        self.indexPath = indexPath
        self.picURLs = picURLs
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- 系统回调函数
    
    override func loadView() {
        super.loadView()
        view.frame.size.width += 15
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        // 1:设置UI界面
        setupUI()
        
        // 2:滚到对应图片的位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        
    }

}

// MARK:- 设置界面相关
extension PhotoBrowserController {
    private func setupUI () {
        // 1:添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        
        // 2:设置尺寸各位置
        collectionView.frame = view.bounds
        closeBtn.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        saveBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(-20)
            make.bottom.equalTo(closeBtn.snp_bottom)
            make.size.equalTo(closeBtn.snp_size)
            
        }
        // 3.设置子控件的属性
        // 3.1.设置collectionView的属性
        collectionView.dataSource = self
        collectionView.registerClass(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCellID)
        
        // 3.2.监听按钮的点击
        closeBtn.addTarget(self, action: #selector(PhotoBrowserController.colseBtnClick), forControlEvents: .TouchUpInside)
        saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveBtnClick), forControlEvents: .TouchUpInside)
    }
    
}

// MARK:- 事件监听函数
extension PhotoBrowserController {
    @objc private func colseBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func saveBtnClick(){
        // 1.取出当前显示的图片
        // 1.1.取出在屏幕中显示的cell
        let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
        
         // 1.2.取出cell中显示的图片
        guard let image = cell.imageView.image else{
            return
        }
        // 2.保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserController.image(_:didFinishSavingWithError:contextInfo:)), nil)
       
    }
    
    @objc private func image(image :UIImage ,didFinishSavingWithError error : NSError?,contextInfo : AnyObject){
        let message = error != nil ? "保存失败" : "保存成功"
        SVProgressHUD.showInfoWithStatus(message)
    }
}

extension PhotoBrowserController : UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 1:取出cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserViewCell
        // 2.给cell设置数据
        cell.picURL = picURLs[indexPath.item]
        cell.delegate = self
        
        return cell
    }
}
// MARK:- cell的代理方法
extension PhotoBrowserController : PhotoBroserViewCellDelegate {
    func imageViewClickForCell(cell: PhotoBrowserViewCell) {
        colseBtnClick()
    }
}
// MARK:- 设置布局
class PhotoBrowserCollectionViewLayout : UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        // 1.设置布局相关
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
        
        // 2.设置collectionView的属性
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}

// MARK:- 提供消失动画的内容
extension PhotoBrowserController : PhotoBrowserDismissDelegate {
    
    func imageViewForDismissView() -> UIImageView {
        // 1.创建UIImageView对象
        let imageView = UIImageView()
        
        // 2.设置图片
        let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
        let image = cell.imageView.image!
        imageView.image = image
        
        // 3.设置frame
        let imageW = UIScreen.mainScreen().bounds.width
        let imageH = imageW / image.size.width * image.size.height
        let imageX : CGFloat = 0
        var imageY : CGFloat = (UIScreen.mainScreen().bounds.height - imageH) * 0.5
        
        imageY = imageY < 0 ? 0 : imageY
        imageView.frame = CGRect(x: imageX, y: imageY, width: imageW, height: imageH)
        
       // 4.设置imageView的内容模式
        imageView.contentMode = .ScaleAspectFit
        imageView.clipsToBounds = true
        
        return imageView
        

    }
    
    func indexPathForDismissView() -> NSIndexPath {
        // 取出当前正在显示的cell
        let cell = collectionView.visibleCells().first!
        
        return collectionView.indexPathForCell(cell)!
    }
    
}






